package com.turbo.cloud.gateway.filter.auth;

import cn.hutool.core.util.StrUtil;
import com.turbo.cloud.gateway.config.AuthProperties;
import com.turbo.cloud.gateway.config.MicroServiceProperties;
import com.turbo.cloud.gateway.config.SecretKey;
import com.turbo.cloud.gateway.utils.PathUtil;
import com.turbo.cloud.gateway.utils.RequestParamUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 接口地址段为interface的秘钥验证
 *
 * @author zhangluning
 */
@RequiredArgsConstructor
@Component
public class InterfaceAuthLogic {

    final MicroServiceProperties microServiceProperties;
    final AuthProperties authProperties;
    /**
     * 验证Interface段接口秘钥
     *
     * @param request 请求
     */
    public boolean validateSecretKey(ServerHttpRequest request) {
        if (!authProperties.getInterfaceAuth().getEnabled()) {
            return true;
        }

        String path = request.getPath().value();
        if (!PathUtil.isInterface(path)) {
            return true;
        }

        /*
         * interface接口，需要验证appId和appKey
         */
        String xAppId = RequestParamUtil.getXAppId(request);
        String xAppKey = RequestParamUtil.getXAppKey(request);

        if (StrUtil.isNotBlank(xAppId) && StrUtil.isNotBlank(xAppKey)) {
            List<SecretKey> secretKeys = microServiceProperties.getSecretKeys();
            if (!CollectionUtils.isEmpty(secretKeys)) {
                for (SecretKey secretKey : secretKeys) {
                    if (xAppId.equals(secretKey.getXAppId()) && xAppKey.equals(secretKey.getXAppKey())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
